<template>
	<view>
		<ksp-cropper mode="fixed" :width="selFileW" :height="selFileH" :url="fileUrl" @cancel="oncancel"
			@ok="onok"></ksp-cropper>
		<view class="gaps">

		</view>
		<view class="add-goods-area">

			<uni-forms ref="form" :rules="rules" :modelValue="form">
				<uni-forms-item label="名称" required name="name">
					<uni-easyinput placeholder="请输入商品名" v-model="form.name" />
				</uni-forms-item>
				<uni-forms-item label="价格" required name="price">
					<uni-easyinput placeholder="0.00" v-model="price" />
				</uni-forms-item>

				<uni-forms-item label="规格">
					<uni-combox :candidates="guiges" placeholder="请选择规格" v-model="form.specification"
						emptyTips=" "></uni-combox>
				</uni-forms-item>
				<uni-forms-item label="起售数量">
					<uni-easyinput placeholder="请输入起售数量" v-model="form.minSaleNum" type="number"/>
				</uni-forms-item>
				<uni-forms-item label="库存">
					<uni-easyinput placeholder="请输入库存" v-model="form.stock" type="number"/>
				</uni-forms-item>
				<uni-forms-item label="划线价" name="topPrice">
					<uni-easyinput placeholder="请输入划线价" v-model="topPrice" type="number"/>
				</uni-forms-item>
				<uni-forms-item label="权重">
					<uni-easyinput placeholder="请输入权重" v-model="form.weight" type="number"/>
				</uni-forms-item>
				<uni-forms-item label="分类">
					<view class="cate-sel" @click="showCate">
						<view>{{showCateName || "请选择分类"}}</view>
						<uni-icons type="bottom" size="20" color="#999999"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item>
					<uni-file-picker title="商品logo" limit="1" file-mediatype="image" :imageStyles="imageStyles"
						mode="grid" @select="selectImage" @delete="delImage">
						<uni-icons type="plusempty" color="#e5e5e5" size="30"></uni-icons>
					</uni-file-picker>
				</uni-forms-item>
				<uni-forms-item>
					<uni-file-picker title="商品展示" limit="9" file-mediatype="image" :imageStyles="detailImageStyles"
						mode="grid" @select="detailSelectImage" @delete="detailDelImage">
						<uni-icons type="plusempty" color="#e5e5e5" size="30"></uni-icons>
					</uni-file-picker>
				</uni-forms-item>


				<uni-forms-item label="描述">
					<uni-easyinput type="textarea" placeholder="描述信息,最多2000字" v-model="form.description" />
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="gaps-bottom">

		</view>

		<view class="bottom-fiex-area">
			<button style="width: 100%;" type="primary" @click="addGoodsForm">确认添加</button>
		</view>

		<uni-popup ref="popup" type="bottom">
			<uni-section title="请选择分类" type="line">
				<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y">
					<uni-list>
						<uni-list-item v-for="(cate,i) in cates" :key="cate.id" clickable @click="cateClick(cate)">
							<template v-slot:body>
								{{cate.name}}({{cate.type == 1 ? "常用分类":"营销分类"}})
							</template>
						</uni-list-item>
					</uni-list>
				</scroll-view>
			</uni-section>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getGoodsType,
	} from '@/api/shops/categoryManage/categoryManage.js'
	import {
		addGoods,
		selectGuige
	} from '@/api/shops/goodsManage/goodsManage.js'
	import uploadFile from '@/utils/uploadFile.js'
	export default {
		data() {
			return {
				cates: {},
				showCateName: '',
				selImage: [],
				detailImage: [],
				eventChannel: undefined,
				guiges: [],
				price:'',
				topPrice:'',
				changeImg:'',
				fileUrl:'',

				form: {
					goodsType: '',
					name: '',
					description: '',
					multimediaUrl: [],
					detailUrl: [],
					specification: '',
					shopId: '',
					price: '',
					minSaleNum:1,
					stock:0,
					topPrice:undefined
				},
				selFileW: 1000,
				selFileH: 1000,
				imageStyles: {
					"height": 80, // 边框高度
					"width": 80, // 边框宽度
					"border": { // 如果为 Boolean 值，可以控制边框显示与否
						"color": "#e5e5e5", // 边框颜色
						"width": "1px", // 边框宽度
						"style": "solid", // 边框样式
						"radius": "5px" // 边框圆角，支持百分比
					}

				},
				detailImageStyles: {
					"height": 100, // 边框高度
					"width": 100, // 边框宽度
					"border": { // 如果为 Boolean 值，可以控制边框显示与否
						"color": "#e5e5e5", // 边框颜色
						"width": "1px", // 边框宽度
						"style": "solid", // 边框样式
						"radius": "5px" // 边框圆角，支持百分比
					}
				},


				rules: {
					// 对name字段进行必填验证
					name: {
						// name 字段的校验规则
						rules: [
							// 校验 name 不能为空
							{
								required: true,
								errorMessage: '请填写商品名',
							},
						],
					},
					price: {
						rules: [{
							required: true,
							errorMessage: '请填写价格',
						}, {
							format: 'number',
							errorMessage: '价格只能输入数字'
						}]
					}
				}
			}
		},
		onLoad: function(option) {
			this.eventChannel = this.getOpenerEventChannel();
			this.form.shopId = option.shopId
			this.init()
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		watch:{
			price(val) {
				if(!val) {
					this.form.price = ''
					return
				}
				if(!isNaN(val)) {
					this.form.price = parseFloat(val * 100).toFixed(0)
				} else {
					this.form.price = val
				}
			},
			topPrice(val) {
				if(!val) {
					this.form.topPrice = ''
					return
				}
				if(!isNaN(val)) {
					this.form.topPrice = parseFloat(val * 100).toFixed(0)
				} else {
					this.form.topPrice = val
				}
			}
		},
		methods: {
			init() {
				selectGuige().then((res) => {
					this.guiges.push(...(res.map(item => item.name)))
				})
			},

			showCate() {
				getGoodsType(this.form.shopId).then(res => {
					if (res.length == 0) {
						return uni.showToast({
							icon: 'none',
							title: '暂无可用分类'
						})
					}

					this.cates = res
					this.$refs.popup.open()

				})
			},
			cateClick(cate) {
				this.$refs.popup.close()
				this.form.goodsType = cate.id
				this.showCateName = cate.name
			},
			oncancel() {
				this.fileUrl = ''
			},

			addGoodsForm(form) {
				let _this = this;
				this.$refs.form.validate().then(res => {
					uni.showLoading({
						title: '正在上传图片'
					})
					// Create an array to stock promises for each image upload
					let uploadPromises = this.selImage.map(item => {
						return uploadFile(item, `shopgoods/${_this.form.shopId}/logo/`).then(url => {
							_this.form.multimediaUrl.push(url.fileUrl)
						})
					})

					uploadPromises.push(...this.detailImage.map(item => {
						return uploadFile(item, `shopgoods/${_this.form.shopId}/detail/`).then(url => {
							_this.form.detailUrl.push(url.fileUrl)
						})
					}))
					// Wait for all the image upload promises to resolve
					Promise.all(uploadPromises).then(() => {
						uni.hideLoading()
						uni.showLoading({
							title: '正在保存商品'
						})
						this.form.multimediaUrl = this.form.multimediaUrl.join(",")
						this.form.detailUrl = this.form.detailUrl.join(',')
						addGoods(this.form).then((res) => {
							this.eventChannel.emit('goodsListChange', {
								data: true
							})
							uni.showModal({
								title: '保存成功,默认在已下架中',
								showCancel: false,
								success() {
									uni.navigateBack()
								}
							})
						})
					}).finally(() => {
						uni.hideLoading()
					})
				})
			},
			selectImage(res) {
				this.changeImg = "logo"
				this.fileUrl = res.tempFilePaths[0]
				// this.selImage.push(...res.tempFilePaths);
			},
			delImage(res) {
				this.selImage.splice(this.selImage.indexOf(res.tempFilePath), 1)
			},
			detailSelectImage(res) {
				this.detailImage.push(...res.tempFilePaths);
			},
			detailDelImage(res) {
				this.detailImage.splice(this.detailImage.indexOf(res.tempFilePath), 1)
			},
			onok(ev) {
				this.fileUrl = '',
				this.selImage.push(ev.path)
			}
		}
	}
</script>

<style lang="scss">
	.add-goods-area {
		background-color: #fff;
		padding: 10px 15px;
	}

	.gaps-bottom {
		height: 60px;
	}

	.bottom-fiex-area {
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2;

	}

	.cate-sel {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		font-size: 13px;
		color: #999999;
		height: 100%;
	}

	.scroll-Y {
		height: 500rpx;
		white-space: nowrap;
		width: 100%;
		background-color: #fff;
	}
</style>